<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Utils\ServerUtil;
use Throwable;
use App\Exception\ValidateException;

class ValidateExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $err = $throwable->getMessage();
        $err_arr = \explode(\config('web.err_msg_splite'), $err);
        $web_err = $err_arr[0];
        $this->stopPropagation();
        $data = json_encode([
            'errCode' => $throwable->getCode(),
            'msg' => $web_err,
            'data'=>[],
        ], JSON_UNESCAPED_UNICODE);
        ServerUtil::info($err, ['line'=>$throwable->getLine(),'file'=>$throwable->getFile()]);

        return $response->withStatus(200)->withBody(new SwooleStream($data));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidateException;
    }
}
